package cn.com.ghy.android.widget.visit;

import java.io.Serializable;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.com.ghy.android.bean.CustomerInfoBean;
import cn.com.ghy.android.bean.DataCollectInfoBean;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.bean.OrderDetailBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.CustOpeService;
import cn.com.ghy.android.service.OrderOpeService;
import cn.com.ghy.android.service.VisitOpeService;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;
import cn.com.ghy.android.widget.chat.OrderInfo;

public class TodayVisit extends Activity {

	private TextView labTxtVisitDate = null;
	private TextView labTxtWayName = null;
	private ListView listCustomerList = null;
	private Intent intent = null;
	private Bundle bundle = null;
	private ProgressDialog progressDialog = null;
	private TextView labTxtCustomerCount = null;
	private ImageButton btnBack = null;

	private String[] taskStateStrArr = null;
	private List<CustomerInfoBean> customerInfoList = null;
	private LoginInfoBean loginInfo = null;

	private CustomerListAdapter customerListAdapter = null;

	private HttpThread httpThread = null;

	private DisposeException disposeException = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.today_visit);
		getSession();
		setToolBar();
		findView();
		init();
		addListener();
	}

	@SuppressWarnings("unchecked")
	private void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		loginInfo = ((ComStaticApp) this.getApplication()).getLoginInfo();
		bundle = this.getIntent().getExtras();
		taskStateStrArr = (String[]) bundle.getStringArray("taskStateStrArr");
		customerInfoList = (List<CustomerInfoBean>) bundle.getSerializable("customerInfoList");
	}

	private void findView() {
		labTxtVisitDate = (TextView) this.findViewById(R.id.labTxtVisitDate);
		labTxtWayName = (TextView) this.findViewById(R.id.labTxtWayName);
		listCustomerList = (ListView) this.findViewById(R.id.listCustomerList);
		labTxtCustomerCount = (TextView) this.findViewById(R.id.labTxtCustomerCount);
	}

	private void setToolBar() {
		View appToolBar = findViewById(R.id.appToolBar);
		ImageButton btnList = (ImageButton) appToolBar.findViewById(R.id.btnList);
		btnList.setVisibility(View.GONE);
		btnBack = (ImageButton) appToolBar.findViewById(R.id.btnBack);
	}

	private void init() {
		labTxtVisitDate.setText(taskStateStrArr[0]);
		labTxtWayName.setText(taskStateStrArr[2]);
		if (null != customerInfoList && customerInfoList.size() > 0) {
			customerListAdapter = new CustomerListAdapter(TodayVisit.this, customerInfoList);
			listCustomerList.setAdapter(customerListAdapter);
			labTxtCustomerCount.setText(customerListAdapter.getCount() + "");
		} else {
			labTxtCustomerCount.setText("0");
		}
	}

	private void addListener() {
		listCustomerList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				showDialog(TodayVisit.this, position,
						(CustomerInfoBean) parent.getItemAtPosition(position));

			}
		});

		btnBack.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				TodayVisit.this.finish();
			}
		});
	}

	private void showDialog(final Context context, final int position,
			final CustomerInfoBean customerInfo) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("提示信息:");
		builder.setMessage("名称:" + customerInfo.getName_org1() + "\n编号:"
				+ customerInfo.getPartner());
		builder.setPositiveButton("进入门店", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				httpThread = new HttpThread(handler);
				httpThread.doStart(CommonStatic.STYPE_E, customerInfo, position);
			}
		});
		builder.setNeutralButton("离开门店", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				httpThread = new HttpThread(handler);
				httpThread.doStart(CommonStatic.STYPE_L, customerInfo, position);
			}
		});
		builder.setNegativeButton("创建订单", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				httpThread = new HttpThread(handler);
				httpThread.doStart("create", customerInfo, position);
			}
		});
		builder.show();
	}

	private class CustomerListAdapter extends BaseAdapter {

		private Context context = null;
		private List<CustomerInfoBean> list = null;

		public CustomerListAdapter(Context context, List<CustomerInfoBean> list) {
			this.context = context;
			this.list = list;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public CustomerInfoBean getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(inflater);
			LinearLayout linearLayout = (LinearLayout) layoutInflater.inflate(
					R.layout.today_visit_lay, null);
			CustomerInfoBean bean = list.get(position);
			TextView tv = (TextView) linearLayout.findViewById(R.id.labTxtCustomerNo);
			tv.setText((position + 1) + ".");

			tv = (TextView) linearLayout.findViewById(R.id.labTxtCustomerName);
			tv.setText(bean.getName_org1());

			tv = (TextView) linearLayout.findViewById(R.id.labTxtCustomerId);
			tv.setText(bean.getPartner());

			tv = (TextView) linearLayout.findViewById(R.id.labTxtIsVisit);
			tv.setText(bean.getIsvisit());

			tv = (TextView) linearLayout.findViewById(R.id.labTxtGrade);
			tv.setText(bean.getDengji());

			tv = (TextView) linearLayout.findViewById(R.id.labTxtIsLeave);
			tv.setText(bean.getIsleave());

			tv = (TextView) linearLayout.findViewById(R.id.labTxtAddress);
			tv.setText(bean.getStreet());
			return linearLayout;
		}

		public void modify(int position, CustomerInfoBean customerInfo) {
			if (position < 0) {
				return;
			}
			list.remove(position);
			list.add(position, customerInfo);
			this.notifyDataSetChanged();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case CommonStatic.INTENT_REQUEST_CODE :
				if (resultCode == RESULT_OK) {
					bundle = data.getExtras();
					String resultStatus = bundle.getString("resultStatus");
					if ("OK".equals(resultStatus)) {
						CustomerInfoBean bean = (CustomerInfoBean) bundle
								.getSerializable("customerInfoForList");
						int todayVisitPosition = bundle.getInt("todayVisitPosition", -1);
						if (todayVisitPosition != -1) {
							customerListAdapter.modify(todayVisitPosition, bean);
						}
					}
				}
				break;
			default :
				break;
		}
	}

	private class HttpThread extends Thread {
		private Handler handle = null;
		private String stype = "";
		private CustomerInfoBean customerInfo = null;
		private int position = -1;

		public HttpThread(Handler hander) {
			handle = hander;
		}

		public void doStart(String stype, CustomerInfoBean customerInfo, int position) {
			this.stype = stype;
			this.customerInfo = customerInfo;
			this.position = position;
			progressDialog = new ProgressDialog(TodayVisit.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			this.start();
		}

		public void run() {
			Message message = null;
			try {
				if (!"create".equals(stype)) {
					String result = null;
					VisitOpeService visitOpeService = new VisitOpeService();
					result = visitOpeService.SetVisitTime(loginInfo, customerInfo.getPartner(),
							taskStateStrArr[1], taskStateStrArr[0], stype);
					if ("OK".equals(result) && stype.equals(CommonStatic.STYPE_E)) {
						DataCollectInfoBean bean = visitOpeService.getVisitDataCollAll(loginInfo,
								customerInfo.getPartner(), taskStateStrArr[1], taskStateStrArr[0]);
						progressDialog.dismiss();
						message = handle.obtainMessage();
						bundle = new Bundle();
						message.what = CommonStatic.STATE_NORMAL;
						bundle.putString("stype", stype);
						bundle.putSerializable("dataCollectInfo", bean);
						bundle.putInt("position", position);
						bundle.putSerializable("customerInfo", customerInfo);
					} else if ("OK".equals(result) && stype.equals(CommonStatic.STYPE_L)) {
						progressDialog.dismiss();
						bundle = new Bundle();
						message = handle.obtainMessage();
						message.what = CommonStatic.STATE_NORMAL;
						bundle.putString("stype", stype);
						bundle.putInt("position", position);
						bundle.putSerializable("customerInfo", customerInfo);
					} else {
						progressDialog.dismiss();
						bundle = new Bundle();
						message = handle.obtainMessage();
						message.what = CommonStatic.STATE_NORMAL_NULL;
						bundle.putString("result", result);
					}
				} else {
					CustOpeService service = new CustOpeService();
					List<CustomerInfoBean> list = service.GetCustShow(customerInfo.getPartner());
					customerInfo = list.get(0);
					OrderOpeService orderOpeService = new OrderOpeService();
					List<OrderDetailBean> listOrderDetail = orderOpeService
							.GetLastMatnr(customerInfo.getPartner());
					progressDialog.dismiss();
					message = handle.obtainMessage();
					bundle = new Bundle();
					message.what = CommonStatic.STATE_NORMAL;
					bundle.putSerializable("customerInfo", customerInfo);
					bundle.putString("stype", stype);
					bundle.putSerializable("listOrderDetail", (Serializable) listOrderDetail);
				}
				message.setData(bundle);
				handle.sendMessage(message);
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}
		}
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(Message m) {
			String result = m.getData().getString("result");
			switch (m.what) {
				case CommonStatic.STATE_NORMAL :
					DataCollectInfoBean bean = (DataCollectInfoBean) m.getData().getSerializable(
							"dataCollectInfo");
					final String stype = m.getData().getString("stype");
					if (!"create".equals(stype)) {
						final int position = m.getData().getInt("position");
						final CustomerInfoBean customerInfo = (CustomerInfoBean) m.getData()
								.getSerializable("customerInfo");
						if (stype.equals(CommonStatic.STYPE_L)) {
							new AlertDialog.Builder(TodayVisit.this).setTitle("提示信息")
									.setMessage("离店成功!")
									.setNeutralButton("关闭", new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dlg, int sumthin) {
											customerInfo.setIsleave("Y");
											customerListAdapter.modify(position, customerInfo);
										}
									}).show();
						} else if (stype.equals(CommonStatic.STYPE_E)) {
							bundle = new Bundle();
							bundle.putSerializable("customerInfo", customerInfo);
							bundle.putStringArray("taskStateStrArr", taskStateStrArr);
							bundle.putInt("position", position);
							bundle.putSerializable("dataCollectInfo", bean);
							intent = new Intent(TodayVisit.this, DataCollect.class);
							intent.putExtras(bundle);
							TodayVisit.this.startActivityForResult(intent,
									CommonStatic.INTENT_REQUEST_CODE);
						}
					} else {
						CustomerInfoBean customerInfoBean = (CustomerInfoBean) m.getData()
								.getSerializable("customerInfo");
						List<OrderDetailBean> listOrderDetail = (List<OrderDetailBean>) m.getData()
								.getSerializable("listOrderDetail");
						bundle = new Bundle();
						bundle.putSerializable("customerInfo", customerInfoBean);
						bundle.putSerializable("listOrderDetail", (Serializable) listOrderDetail);
						intent = new Intent(TodayVisit.this, OrderInfo.class);
						intent.putExtras(bundle);
						TodayVisit.this.startActivity(intent);
					}
					break;
				case CommonStatic.STATE_NORMAL_NULL :
					new AlertDialog.Builder(TodayVisit.this).setTitle("提示信息").setMessage(result)
							.setNeutralButton("关闭", null).show();
					break;
			}
		}
	};
}
